package com.heqiang.spring.beans.factory.support;

import com.heqiang.spring.beans.BeansException;
import com.heqiang.spring.beans.factory.FactoryBean;
import com.heqiang.spring.beans.factory.config.BeanDefinition;
import com.heqiang.spring.beans.factory.config.BeanPostProcessor;
import com.heqiang.spring.beans.factory.config.ConfigurableBeanFactory;
import com.heqiang.spring.util.ClassUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    private List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

    @Override
    public Object getBean(String name) throws BeansException {
       return doGetBean(name,null);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return (T) getBean(name);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name,args);
    }

    protected <T> T doGetBean(final String name,final Object[] args) {
        //先从单例里拿，有就直接返回
        Object singleton = getSingleton(name);
        if (singleton != null) {
            // 如果是 FactoryBean，则需要调用 FactoryBean#getObject
            return (T) getObjectFromBeanInstance(singleton,name);
        }
        //单例容器里没有就新增一个
        BeanDefinition beanDefinition = getBeanDefinition(name);
        Object bean = createBean(name,beanDefinition,args);
        return (T) getObjectFromBeanInstance(bean,name);
    }

    private Object getObjectFromBeanInstance (Object beanINstance,String beanName) {
        if (!(beanINstance instanceof FactoryBean)) {
            return beanINstance;
        }
        Object object = getCachedObjectForFactoryBean(beanName);
        if (Objects.isNull(object)) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanINstance;
            object = getObjectFromFactoryBean(factoryBean,beanName);
        }
        return object;
    }

    protected abstract BeanDefinition getBeanDefinition(String name) throws BeansException;

    protected abstract Object createBean(String name,BeanDefinition beanDefinition,Object[] args) throws BeansException;

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return beanPostProcessors;
    }

    public ClassLoader getBeanClassLoader () {
        return this.beanClassLoader;
    }
}
